#!/usr/bin/env bash

# Copyright 2016 The Fuchsia Authors
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

# This script downloads firmware as prebuilts from Google Storage.

# This script is expected to be executed by Jiri as a runhook, or by individual
# developers who want to grab the latest prebuilts.  It takes no arguments, will
# download the latest version of the firmware, install it in the
# prebuilt/downloads directory, and update prebuilt/config.mk with the firmware
# prefix (so you shouldn't have to set PATH or anything yourself).

set -e

readonly GS_BUCKET="https://fuchsia-build.storage.googleapis.com"

# We assume the following directory structure:
# ./zircon/scripts
# ./zircon/prebuilt
readonly SCRIPT_DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
readonly ZIRCON_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly PREBUILTS_DIR="$(cd "${ZIRCON_ROOT}/prebuilt" && pwd)"

# Install prebuilts into a .gitignore'd directory to keep things clean
mkdir -p "${PREBUILTS_DIR}/downloads/firmware"
readonly INSTALL_DIR="$(cd "${PREBUILTS_DIR}/downloads/firmware" && pwd)"

# Download the tools if they don't already exist, or if their versions are out of date.
TOOLCHAIN_MAKEVARS=()
PREBUILT_NAMES=()
function downloadFirmware() {
  local target="${1}"

  # These are files and paths we expect to already exist.
  local common_path="firmware/${target}"
  local version_file="${PREBUILTS_DIR}/versions/${common_path}/version.sha"
  if [[ ! -f "${version_file}" ]]; then
    echo "File ${version_file} does not exist."
    echo "Your operating system is probably not supported, aborting."
    exit 1
  fi
  local required_version="$(cat "${version_file}" )"
  local prebuilt_url="${GS_BUCKET}/${common_path}/${required_version}"

  # These are files and paths we control in this script.
  local tool_name="${target}"
  local stamp_path="${INSTALL_DIR}/${tool_name}/${tool_name}.stamp"
  local tool_path="${INSTALL_DIR}/${tool_name}/${tool_name}.zip"

  # The stamp file contains the SHA of the last version we downloaded.  If it doesn't
  # match the SHA found in the version file, download and unpack the new one.
  cd ${INSTALL_DIR}
  mkdir -p "${target}"
  cd "${target}"
  if [[ ! -f "${stamp_path}" || "${required_version}" != "$(cat ${stamp_path})" ]]; then
    rm -f -- "${tool_path}"
    echo "Downloading ${prebuilt_url}"
    curl --progress-bar -continue-at=- --location --output "${tool_path}" "${prebuilt_url}"
    echo "Unpacking ${tool_path}"
    unzip -qo "${tool_path}"
    echo "${required_version}" > "${stamp_path}"
  fi
}

# We want the firmware for all target types.
readonly TARGETS=("ovmf")
for target in "${TARGETS[@]}"; do
  downloadFirmware "${target}"
done
